package com.han.verifycode.ver.exact;

import com.han.verifycode.CodeConfig;
import com.han.verifycode.data.Answer;
import com.han.verifycode.data.CalcExpression;
import com.han.verifycode.data.FullPath;
import com.han.verifycode.data.RightKey;
import com.han.verifycode.enums.VerifyCodeEnum;
import com.han.verifycode.utils.CalcUtil;
import com.han.verifycode.utils.DrawCodeUtil;
import com.han.verifycode.ver.ExactMatchCode;
import com.han.verifycode.ver.conf.CalcNumConf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 数字计算
 */
public class CalcNumCode implements ExactMatchCode {
    private CalcNumConf thisConf;
    private VerifyCodeEnum type = VerifyCodeEnum.CalcNum;

    @Override
    public RightKey generate(String code, CodeConfig conf) {
        RightKey key = new RightKey(code);
        if (conf == null) {
            thisConf = new CalcNumConf();
        } else {
            thisConf = (CalcNumConf) conf;
        }
        key.setConfig(thisConf);
        key.setType(type);
        key.setTips("请输入图片中算式计算结果");
        key.setWidth(conf.getWidth());
        key.setHeight(conf.getHeight());

        CalcExpression exp = CalcUtil.randomExpression(thisConf.getLength(), thisConf.getMaxNum());
        key.setAnswer(exp.getResult());
        key.setDesc(exp.getDesc());
        FullPath rfilePath = generateFilePath(thisConf.getBasePath(), key.getCode());
        key.setFullPath(rfilePath);
        draw(thisConf, key);
        return key;
    }

    private void draw(CalcNumConf conf, RightKey key) {
        String filePath = key.getFullPath().getAbsolutePath();
        FileOutputStream f = null;
        try {
            f = new FileOutputStream(new File(filePath));
            DrawCodeUtil.outputImage(thisConf.getWidth().intValue(), thisConf.getHeight().intValue(), f, key.getDesc(), thisConf.isSalt(), false);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (f != null) {
                try {
                    f.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    @Override
    public CodeConfig getConfig() {
        return thisConf;
    }


    public boolean verify(Answer answer) {
        return false;
    }
}
